// component/useDynamicRoutes.js
import { useState, useEffect } from 'react';
import { Route } from 'react-router-dom';

const useDynamicRoutes = (permissions, loading, error, routeConfig) => {
    const [routes, setRoutes] = useState([]);
    const [previousPermissions, setPreviousPermissions] = useState(null);
    const [routesKey, setRoutesKey] = useState(0);

    useEffect(() => {
        // 每次依赖项变化时打印当前状态
        console.log('useDynamicRoutes effect 触发');

        // 只有当加载完成并且没有错误时才生成新路由
        if (!loading && !error) {
            console.log('检查是否需要更新路由...');

            // 检查 permissions 是否是非空数组
            const hasPermissions = Array.isArray(permissions) && permissions.length > 0;
            console.log('权限是否存在且非空:', hasPermissions);

            // 比较新的权限和旧的权限是否相同
            let permissionsChanged = previousPermissions === null ||
                JSON.stringify(previousPermissions.sort()) !== JSON.stringify(permissions.sort());
            console.log('权限是否发生变化:', permissionsChanged);

            // 如果 permissions 是非空数组，并且确实发生了变化，则更新路由
            if (hasPermissions && permissionsChanged) {
                console.log('权限已改变，正在更新路由...');

                // 更新权限状态
                setPreviousPermissions([...permissions]);
                console.log('已更新 previousPermissions:', previousPermissions);

                // 生成新的路由
                const newRoutes = routeConfig
                    .filter(route => permissions.includes(route.permission))
                    .map(({ path, component: Component }) => (
                        <Route key={path} path={path} element={<Component />} />
                    ));

                setRoutes(newRoutes);
                console.log("路由已经更新，新的路由为:", newRoutes);

                // 增加 routesKey 以强制重新挂载 Routes
                setRoutesKey(prevKey => prevKey + 1);
                console.log('增加 routesKey 以强制重新挂载 Routes');
            } else {
                console.log('权限未发生变化，不更新路由');
            }
        } else {
            console.log('仍在加载或存在错误，不更新路由');
        }
    }, [permissions, loading, error, routeConfig, previousPermissions]);

    return [routes, routesKey];
};

export default useDynamicRoutes;